package com.tencent.ymcc.web.controller;

import com.tencent.ymcc.result.JSONResult;
import com.tencent.ymcc.result.PageList;
import com.tencent.ymcc.service.IEmployeeService;
import com.tencent.ymcc.domain.Employee;
import com.tencent.ymcc.query.EmployeeQuery;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    public IEmployeeService employeeService;

    /**
    * 保存和修改公用的
    */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public JSONResult saveOrUpdate(@RequestBody @Valid Employee employee){
        // 校验空值

        // 常规 if else if
//        if (StringUtils.isBlank(employee.getEmail())) {
//            throw  new GlobalCustomException("Email不能为空", "8888");
//        } else if (StringUtils.isBlank(employee.getRealName())) {
//            throw  new GlobalCustomException("用户名不能为空", "8889");
//        }  复杂麻烦

        // 写很多 所以加一个枚举常量类来管理      ---  抛出业务异常的时候
//        AssertUtil.isNotEmpty(employee.getRealName(), "用户名不能为空", "20002");
//
//        // 断言 + 枚举类
//        AssertUtil.isNotEmpty(employee.getEmail(),
//                Constances.EMAIL_NOT_BLANK.getMessgae(),
//                Constances.EMAIL_NOT_BLANK.getCode());

        // 但是万一字段很多呢 也很麻烦 我们使用JSR303来做参数的校验    --- 表单数据提交
        // 在pojo实体类导包spring-boot-starter-validation 在参数前加 @Vaild注解 开启校验




        if(employee.getId()!=null){
            employeeService.updateById(employee);
        }else{
            employeeService.insert(employee);
        }
        return JSONResult.success();
    }

    /**
    * 删除对象
    */
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    public JSONResult delete(@PathVariable("id") Long id){
        System.out.println(id);
        employeeService.deleteById(id);
        return JSONResult.success();
    }

    /**
      * 获取对象
      */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public JSONResult get(@PathVariable("id")Long id){
        return JSONResult.success(employeeService.selectById(id));
    }


    /**
    * 查询所有对象
    */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public JSONResult list(){
        return JSONResult.success(employeeService.selectList(null));
    }


    /**
    * 带条件分页查询数据
    */
    @RequestMapping(value = "/pagelist",method = RequestMethod.POST)
    public JSONResult page(@RequestBody EmployeeQuery query){
        Page<Employee> page = new Page<Employee>(query.getPage(),query.getRows());
        page = employeeService.selectPage(page);
        return JSONResult.success(new PageList<Employee>(page.getTotal(),page.getRecords()));
    }

}
